package top.roadvast.rabbitmq.consumer;

import com.rabbitmq.client.*;
import top.roadvast.rabbitmq.utils.RabbitmqUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 15:44
 * @Version 1.0
 * @Description
 */
public class TopicConsumer {
    public static void main(String[] args) throws IOException {
        final Connection connection = RabbitmqUtil.getConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);
        final String queueName = channel.queueDeclare().getQueue();
        System.out.println("输入bindingKey，用,分隔开");
        //绑定关系，例如：[*.lucy],[info.*]
        final String bindingKeyStr = new Scanner(System.in).nextLine();
        final String[] bindingKeys = bindingKeyStr.split(",");
        System.out.println("等待接收数据...");
        for (String bindingKey : bindingKeys) {
            //队列，交换机，routingKey
            channel.queueBind(queueName, "topic_logs", bindingKey);
        }
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            final String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            final String routingKey = message.getEnvelope().getRoutingKey();
            System.out.println("接收到消息：msg=" + msg + ",routingKey=" + routingKey);
        };
        CancelCallback cancelCallback = (consumerTag) -> {

        };
        channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
    }
}
